"""
用户管理服务 API
所有接口采用 POST 方法，统一响应格式
"""
from fastapi import APIRouter, Depends, Request
from motor.motor_asyncio import AsyncIOMotorDatabase
from pydantic import BaseModel, Field
from typing import List, Optional
from bson import ObjectId
from datetime import datetime

from database.connection import get_database
from models.user import UserOut
from api.deps_v1 import get_current_user, get_current_admin
from utils.response import success, error
from models.response import ErrorCode

router = APIRouter(prefix="/sac/v1/User", tags=["用户管理服务"])

# 服务名称
SERVICE_NAME = "User"


# ========== 请求模型 ==========

class ListUsersRequest(BaseModel):
    """获取用户列表请求"""
    skip: int = Field(default=0, ge=0, description="跳过记录数")
    limit: int = Field(default=10, ge=1, le=100, description="返回记录数")


class GetUserRequest(BaseModel):
    """获取指定用户请求"""
    user_id: str = Field(..., description="用户ID")


class BanUserRequest(BaseModel):
    """封禁用户请求"""
    user_id: str = Field(..., description="用户ID")


class UnbanUserRequest(BaseModel):
    """解封用户请求"""
    user_id: str = Field(..., description="用户ID")


# ========== 响应模型 ==========

class ListUsersResult(BaseModel):
    """用户列表结果"""
    users: List[UserOut]
    total: int
    skip: int
    limit: int


class GetUserResult(BaseModel):
    """用户信息结果"""
    user: UserOut


class BanUserResult(BaseModel):
    """封禁用户结果"""
    message: str
    user_id: str


class UnbanUserResult(BaseModel):
    """解封用户结果"""
    message: str
    user_id: str


# ========== API 接口 ==========

@router.post("/ListUsers", summary="获取用户列表（仅管理员）")
async def list_users(
    request: Request,
    body: ListUsersRequest,
    admin: dict = Depends(get_current_admin),
    db: AsyncIOMotorDatabase = Depends(get_database)
):
    """
    获取所有用户列表（分页）
    
    **权限**: 仅管理员
    """
    try:
        # 查询用户总数
        total = await db.users.count_documents({})
        
        # 查询用户列表
        cursor = db.users.find().skip(body.skip).limit(body.limit)
        users = await cursor.to_list(length=body.limit)
        
        # 转换数据格式
        user_list = []
        for user in users:
            user["id"] = str(user.pop("_id"))
            user_list.append(UserOut(**user))
        
        return success(
            request, "ListUsers", SERVICE_NAME,
            ListUsersResult(
                users=user_list,
                total=total,
                skip=body.skip,
                limit=body.limit
            ).model_dump()
        )
        
    except Exception as e:
        return error(
            request, "ListUsers", SERVICE_NAME,
            ErrorCode.SYSTEM_ERROR,
            detail=str(e)
        )


@router.post("/GetUser", summary="获取指定用户信息（仅管理员）")
async def get_user(
    request: Request,
    body: GetUserRequest,
    admin: dict = Depends(get_current_admin),
    db: AsyncIOMotorDatabase = Depends(get_database)
):
    """
    获取指定用户的详细信息
    
    **权限**: 仅管理员
    """
    try:
        # 验证 ObjectId 格式
        if not ObjectId.is_valid(body.user_id):
            return error(
                request, "GetUser", SERVICE_NAME,
                ErrorCode.INVALID_PARAMETER,
                detail="无效的用户ID格式"
            )
        
        # 查询用户
        user = await db.users.find_one({"_id": ObjectId(body.user_id)})
        
        if not user:
            return error(
                request, "GetUser", SERVICE_NAME,
                ErrorCode.USER_NOT_FOUND
            )
        
        user["id"] = str(user.pop("_id"))
        
        return success(
            request, "GetUser", SERVICE_NAME,
            GetUserResult(user=UserOut(**user)).model_dump()
        )
        
    except Exception as e:
        return error(
            request, "GetUser", SERVICE_NAME,
            ErrorCode.SYSTEM_ERROR,
            detail=str(e)
        )


@router.post("/BanUser", summary="封禁用户（仅管理员）")
async def ban_user(
    request: Request,
    body: BanUserRequest,
    admin: dict = Depends(get_current_admin),
    db: AsyncIOMotorDatabase = Depends(get_database)
):
    """
    封禁指定用户
    
    **权限**: 仅管理员  
    **注意**: 不能封禁其他管理员
    """
    try:
        # 验证 ObjectId 格式
        if not ObjectId.is_valid(body.user_id):
            return error(
                request, "BanUser", SERVICE_NAME,
                ErrorCode.INVALID_PARAMETER,
                detail="无效的用户ID格式"
            )
        
        # 更新用户状态（不能封禁其他 admin）
        result = await db.users.update_one(
            {"_id": ObjectId(body.user_id), "role": "user"},
            {"$set": {"disabled": True, "updated_at": datetime.utcnow()}}
        )
        
        if result.matched_count == 0:
            return error(
                request, "BanUser", SERVICE_NAME,
                ErrorCode.INVALID_OPERATION,
                message="用户不存在或无法封禁管理员"
            )
        
        return success(
            request, "BanUser", SERVICE_NAME,
            BanUserResult(
                message=f"用户 {body.user_id} 已被封禁",
                user_id=body.user_id
            ).model_dump()
        )
        
    except Exception as e:
        return error(
            request, "BanUser", SERVICE_NAME,
            ErrorCode.SYSTEM_ERROR,
            detail=str(e)
        )


@router.post("/UnbanUser", summary="解封用户（仅管理员）")
async def unban_user(
    request: Request,
    body: UnbanUserRequest,
    admin: dict = Depends(get_current_admin),
    db: AsyncIOMotorDatabase = Depends(get_database)
):
    """
    解封指定用户
    
    **权限**: 仅管理员
    """
    try:
        # 验证 ObjectId 格式
        if not ObjectId.is_valid(body.user_id):
            return error(
                request, "UnbanUser", SERVICE_NAME,
                ErrorCode.INVALID_PARAMETER,
                detail="无效的用户ID格式"
            )
        
        # 更新用户状态
        result = await db.users.update_one(
            {"_id": ObjectId(body.user_id)},
            {"$set": {"disabled": False, "updated_at": datetime.utcnow()}}
        )
        
        if result.matched_count == 0:
            return error(
                request, "UnbanUser", SERVICE_NAME,
                ErrorCode.USER_NOT_FOUND
            )
        
        return success(
            request, "UnbanUser", SERVICE_NAME,
            UnbanUserResult(
                message=f"用户 {body.user_id} 已被解封",
                user_id=body.user_id
            ).model_dump()
        )
        
    except Exception as e:
        return error(
            request, "UnbanUser", SERVICE_NAME,
            ErrorCode.SYSTEM_ERROR,
            detail=str(e)
        )

